<template>
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item>咨询师信息管理</el-breadcrumb-item>
		<el-breadcrumb-item>咨询师收费标准管理</el-breadcrumb-item>
	</el-breadcrumb>

	<el-form :inline="true" :model="queryInfo" class="demo-form-inline" style="padding: 15px 0;">
		<el-form-item label="咨询师姓名">
			<el-input v-model="queryInfo.counselor.counselorName" placeholder="请输入咨询师姓名" clearable
				@clear="queryDataList" />
		</el-form-item>

		<el-form-item>
			<el-button type="primary" @click="queryDataList">搜索</el-button>
			<el-button type="primary" @click="add">新增收费标准</el-button>
			<el-button type="danger" @click="batchRemove">批量删除</el-button>
		</el-form-item>
	</el-form>

	<el-table :data="dataList" border row-key="id" style="width: 100%" @selection-change="handleSelectionChange">
		<el-table-column type="selection" width="55" />
		<el-table-column property="id" label="ID" width="100" />
		<!-- 收费分类：绑定后端嵌套对象 -->
		<el-table-column label="收费分类类别" align="center">
			<template #default="scope">
				{{ scope.row.counselorPriceClassify?.priceClassifyName || '未知' }}
			</template>
		</el-table-column>
		<el-table-column property="price" label="收费价格" align="center" />
		<!-- 移除“咨询数量”列 -->
		<!-- 咨询师姓名：绑定后端嵌套对象 -->
		<el-table-column label="咨询师姓名" align="center">
			<template #default="scope">
				{{ scope.row.counselor?.counselorName || '未知' }}
			</template>
		</el-table-column>

		<el-table-column fixed="right" label="操作" min-width="120">
			<template #default="scope">
				<el-button type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
				<el-button type="danger" size="small" @click="remove(scope.row.id)">删除</el-button>
			</template>
		</el-table-column>
	</el-table>

	<el-pagination v-model:current-page="queryInfo.pageNum" v-model:page-size="queryInfo.pageSize"
		:page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="total"
		@size-change="handleSizeChange" @current-change="handleCurrentChange" />

	<el-dialog :title="title" v-model="dialogFormVisible" width="600" @close="cancle">
		<el-form :model="formData" label-width="120px">
			<!-- 收费分类 -->
			<el-form-item label="收费分类" prop="priceClassifyId">
				<el-select v-model="formData.priceClassifyId" placeholder="请选择收费分类" style="width: 100%">
					<el-option v-for="classify in priceClassifyList" :key="classify.id" :value="classify.id"
						:label="classify.priceClassifyName" />
				</el-select>
			</el-form-item>

			<!-- 收费价格 -->
			<el-form-item label="收费价格" prop="price">
				<el-input v-model="formData.price" placeholder="请输入收费价格" />
			</el-form-item>

			<!-- 移除“咨询数量”表单项 -->

			<!-- 咨询师 -->
			<el-form-item label="咨询师" prop="counselorId">
				<el-select v-model="formData.counselorId" placeholder="请选择咨询师" style="width: 100%">
					<el-option v-for="counselor in counselorList" :key="counselor.id" :value="counselor.id"
						:label="counselor.counselorName" />
				</el-select>
			</el-form-item>
		</el-form>

		<template #footer>
			<el-button @click="cancle">取 消</el-button>
			<el-button type="primary" @click="confirm">确 定</el-button>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
	import { ElMessage, ElMessageBox } from 'element-plus';
	import { getCurrentInstance, onMounted, reactive, ref } from 'vue';
	import qs from 'qs';

	// 类型定义（移除consultNumber相关）
	interface Counselor {
		id ?: number;
		counselorName ?: string;
	}
	interface CounselorPriceClassify {
		id ?: number;
		priceClassifyName ?: string;
	}
	interface QueryInfo {
		counselor : {
			counselorName : string;
		};
		pageNum : number;
		pageSize : number;
	}

	// 全局axios实例
	const axios = getCurrentInstance().appContext.config.globalProperties.axios;

	// 查询参数
	const queryInfo = reactive<QueryInfo>({
		counselor: {
			counselorName: ''
		},
		pageNum: 1,
		pageSize: 10
	});

	// 数据列表与总数
	const dataList = ref<any[]>([]);
	const total = ref(0);

	// 下拉选项数据
	const priceClassifyList = ref<CounselorPriceClassify[]>([]);
	const counselorList = ref<Counselor[]>([]);

	// 表单数据（移除consultNumber字段）
	const formData = ref({
		id: '',
		priceClassifyId: null as number | null,
		counselorId: null as number | null,
		price: null as number | null
	});

	// 对话框状态
	const dialogFormVisible = ref(false);
	const title = ref('新增收费标准');

	// 批量选择的ID列表
	const multipleSelection = ref<number[]>([]);

	// 加载下拉选项数据
	const loadSelectData = () => {
		// 加载收费分类列表
		axios.get('/counselorPriceClassify')
			.then(resp => {
				if (resp.code === 200) {
					priceClassifyList.value = resp.data;
				} else {
					ElMessage.error('加载收费分类失败: ' + (resp.msg || '未知错误'));
				}
			})
			.catch(err => {
				console.error('收费分类加载错误:', err);
				ElMessage.error('网络错误，无法加载收费分类');
			});

		// 加载咨询师列表
		axios.get('/counselor')
			.then(resp => {
				if (resp.code === 200) {
					counselorList.value = resp.data;
				} else {
					ElMessage.error('加载咨询师列表失败: ' + (resp.msg || '未知错误'));
				}
			})
			.catch(err => {
				console.error('咨询师列表加载错误:', err);
				ElMessage.error('网络错误，无法加载咨询师');
			});
	};

	// 查询数据列表
	const queryDataList = () => {
		axios.get('/counselorPriceStandard/page', {
			params: queryInfo,
			paramsSerializer: (params) => qs.stringify(params, { allowDots: true })
		})
			.then((resp) => {
				if (resp.code === 200) {
					dataList.value = resp.data.list;
					total.value = resp.data.total;
				} else {
					ElMessage.error('查询失败: ' + (resp.msg || '未知错误'));
				}
			})
			.catch(err => {
				console.error('查询接口错误:', err);
				ElMessage.error('网络错误，无法查询数据');
			});
	};

	// 分页处理
	const handleSizeChange = (val : number) => {
		queryInfo.pageSize = val;
		queryInfo.pageNum = 1;
		queryDataList();
	};
	const handleCurrentChange = (val : number) => {
		queryInfo.pageNum = val;
		queryDataList();
	};

	// 表格选择变化
	const handleSelectionChange = (val : any[]) => {
		multipleSelection.value = val.map(item => item.id);
	};

	// 新增操作（表单移除consultNumber）
	const add = () => {
		title.value = '新增收费标准';
		formData.value = {
			id: '',
			priceClassifyId: null,
			counselorId: null,
			price: null
		};
		dialogFormVisible.value = true;
		loadSelectData();
	};

	// 编辑操作（移除consultNumber赋值）
	const edit = (row : any) => {
		title.value = '编辑收费标准';
		formData.value = {
			id: row.id,
			priceClassifyId: row.priceClassifyId,
			counselorId: row.counselorId,
			price: row.price
		};
		dialogFormVisible.value = true;
		loadSelectData();
	};

	// 取消操作
	const cancle = () => {
		dialogFormVisible.value = false;
	};

	// 确认提交（移除consultNumber验证）
	const confirm = () => {
		// 表单验证（仅验证剩余字段）
		if (formData.value.priceClassifyId === null) {
			ElMessage.warning('请选择收费分类');
			return;
		}
		if (formData.value.counselorId === null) {
			ElMessage.warning('请选择咨询师');
			return;
		}
		if (formData.value.price === null || isNaN(Number(formData.value.price))) {
			ElMessage.warning('请输入有效的收费价格');
			return;
		}

		// 提交请求
		const request = formData.value.id
			? axios.put('/counselorPriceStandard', formData.value)
			: axios.post('/counselorPriceStandard', formData.value);

		request.then(resp => {
			if (resp.code === 200) {
				ElMessage.success(formData.value.id ? '修改成功' : '新增成功');
				dialogFormVisible.value = false;
				queryDataList();
			} else {
				ElMessage.error((formData.value.id ? '修改失败' : '新增失败') + ': ' + (resp.msg || '操作失败'));
			}
		}).catch(err => {
			console.error('提交接口错误:', err);
			ElMessage.error('网络错误，无法提交数据');
		});
	};

	// 单个删除
	const remove = (id : number) => {
		ElMessageBox.confirm(
			'此操作将永久删除该收费标准，是否继续?',
			'确认删除',
			{ type: 'warning' }
		).then(() => {
			axios.delete(`/counselorPriceStandard/${id}`)
				.then(resp => {
					if (resp.code === 200) {
						ElMessage.success('删除成功');
						queryDataList();
					} else {
						ElMessage.error('删除失败: ' + (resp.msg || '删除失败'));
					}
				})
				.catch(err => {
					console.error('删除接口错误:', err);
					ElMessage.error('网络错误，无法删除');
				});
		}).catch(() => {
			ElMessage.info('已取消删除');
		});
	};

	// 批量删除
	const batchRemove = () => {
		if (multipleSelection.value.length === 0) {
			ElMessage.warning('请先选择要删除的记录');
			return;
		}

		ElMessageBox.confirm(
			`此操作将永久删除选中的 ${multipleSelection.value.length} 条记录，是否继续?`,
			'批量删除',
			{ type: 'warning' }
		).then(() => {
			axios.delete('/counselorPriceStandard', {
				params: { ids: multipleSelection.value.join(',') }
			}).then(resp => {
				if (resp.code === 200) {
					ElMessage.success('批量删除成功');
					queryDataList();
				} else {
					ElMessage.error('批量删除失败: ' + (resp.msg || '删除失败'));
				}
			}).catch(err => {
				console.error('批量删除接口错误:', err);
				ElMessage.error('网络错误，无法批量删除');
			});
		}).catch(() => {
			ElMessage.info('已取消批量删除');
		});
	};

	// 页面初始化
	onMounted(() => {
		queryDataList();
	});
</script>

<style scoped>
	.el-breadcrumb {
		border-bottom: 1px solid #EEEEEE;
		padding-bottom: 15px;
		margin-bottom: 20px;
	}

	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}

	.el-table {
		margin-bottom: 20px;
	}

	.el-pagination {
		margin-top: 15px;
		text-align: right;
	}

	.el-select {
		width: 100%;
	}
</style>